import * as amqp from 'amqplib';

const rabbitMQServer = "amqp://mingcai_mq:EUDNfpZRbhfjb8PZ@95.169.25.181";

async function consume() {
    const connection = await amqp.connect(rabbitMQServer);
    const channel = await connection.createChannel();
    const queue = 'work_queue';

    await channel.assertQueue(queue, {durable: true});
    // 设置每次只处理一个消息
    //这一行代码的作用是告诉 RabbitMQ 不要在消费者未确认（ack）之前向其发送新的消息
    await channel.prefetch(1);

    console.log(' [*] Waiting for messages. To exit press CTRL+C');

    await channel.consume(queue, async (msg) => {
        if (msg !== null) {
            const message = msg.content.toString();
            console.log(` [x] Received ${message}`);

            // Simulate some work
            await new Promise(resolve => setTimeout(resolve, 1000));

            console.log(' [x] Done');
            channel.ack(msg);
        }
    });
}

consume();
